import { cameraActive, moveToCamera } from './cameraModule.js';
import { showToast } from './uiEffects.js';

// 分析图像
async function selectImageForAnalysis(imageSrc, imageName) {
    const progressBar = document.getElementById('global-progress');
    
    try {
        progressBar.classList.add('active');
        
        const selectedImage = document.getElementById('selectedImage');
        const noImagePlaceholder = document.querySelector('.no-image-placeholder');
        
        // 将dataURL转换为Blob
        const blob = await fetch(imageSrc).then(res => res.blob());
        
        // 创建FormData并添加图片文件
        const formData = new FormData();
        formData.append('image', blob, 'tongue.jpg');

        // 发送到后端API tongue.dianchuang.club 端口6066 nginx反向代理/api/
        const response = await fetch('https://tongue.dianchuang.club/api/upload', {
            method: 'POST',
            body: formData
        });

        if (!response.ok) throw new Error(`分析失败: ${response.status}`);
        const result = await response.json();
        console.log(result)

        // 显示图片和结果
        selectedImage.src = imageSrc;
        selectedImage.style.display = 'block';
        noImagePlaceholder.style.display = 'none';
        updateProbabilities(result);
        
        // 显示成功提示
        showToast('舌象分析成功', 'success');

    } catch (error) {
        showToast('图片像素应该为384x384');
    }
    finally {
        progressBar.classList.remove('active');
        moveToCamera();
        
        // 如果是从相机拍照分析的，保持相机开启状态
        if (cameraActive && document.getElementById('photoConfirmControls').style.display === 'flex') {
            // 删除"上传分析"按钮，只保留"重拍一张"按钮
            const confirmPhotoBtn = document.getElementById('confirmPhotoBtn');
            if (confirmPhotoBtn) {
                confirmPhotoBtn.style.display = 'none';
            }

            // 修改"重拍一张"按钮的文本为"再拍一张"
            const retakePhotoBtn = document.getElementById('retakePhotoBtn');
            if (retakePhotoBtn) {
                retakePhotoBtn.textContent = '再拍一张';
            }
        }

    }
}

// 更新概率显示的实际函数
function updateProbabilities(data) {
    const probabilityItems = document.querySelectorAll('.probability-item');
    
    // 维度分类与中文映射
    const dimensionConfig = {
        color: {
            prefix: 'colorResult_',
            label: '舌色'
        },
        shape: {
            prefix: 'shapeResult_',
            label: '舌形'
        },
        texture: {
            prefix: 'textureResult_',
            label: '舌质'
        },
        thickness: {
            prefix: 'thicknessResult_',
            label: '苔质'
        }
    };

    // 完整中文映射表
    const labelMapping = {
        'colorResult_grey': '偏灰',
        'colorResult_white': '偏白',
        'colorResult_yellow': '偏黄',
        'shapeResult_ToothMarks': '齿痕',
        'shapeResult_fat': '胖大',
        'shapeResult_normal': '正常',
        'shapeResult_thin': '瘦薄',
        'textureResult_dark': '暗沉',
        'textureResult_normal': '正常',
        'textureResult_tender': '娇嫩',
        'textureResult_water': '水滑',
        'thicknessResult_Stripping': '剥落',
        'thicknessResult_ecchymosis': '瘀斑',
        'thicknessResult_greasy': '厚腻',
        'thicknessResult_thin': '薄白'
    };

    // 获取每个维度的最高概率结果
    const dimensionResults = Object.entries(dimensionConfig).map(([dim, config]) => {
        const entries = Object.entries(data.results)
            .filter(([key]) => key.startsWith(config.prefix))
            .sort((a, b) => b[1] - a[1]);
        
        console.log({
            dimension: config.label,
            key: entries[0]?.[0] || '',
            value: entries[0]?.[1] || 0
        });
        

        return {
            dimension: config.label,
            key: entries[0]?.[0] || '',
            value: entries[0]?.[1] || 0
        };
    });

    // 更新每个概率项
    probabilityItems.forEach((item, index) => {
        const result = dimensionResults[index];
        const labelElement = item.querySelector('.probability-label');
        const barElement = item.querySelector('.probability-bar');
        const valueElement = item.querySelector('.probability-value');

        if (result) {
            const chineseLabel = labelMapping[result.key] || result.key;
            const percentage = Math.round(result.value * 100);
            
            // 示例显示："舌色 - 偏白"
            labelElement.textContent = `${result.dimension} - ${chineseLabel}`;
            barElement.style.width = `${percentage}%`;
            valueElement.textContent = `${percentage}%`;
        }
    });
}

export { selectImageForAnalysis, updateProbabilities };